﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Web.Security;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;

namespace SoftwareDiscipline.SharePoint.UserManagement.ApplicationPages
{

    /// <summary>
    /// 
    /// </summary>
    public partial class AssignRoles : LayoutsPageBase
    {
        /// <summary>
        /// 
        /// </summary>
        private string userName = String.Empty;

        /// <summary>
        /// Represents that method that handles the <see cref="E:System.Web.UI.Control.Load"/> event of the page.
        /// </summary>
        /// <param name="e">A <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // bind roles to the check box list
            if (!this.Page.IsPostBack)
            {
                SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                if (webApp != null)
                {
                    SqlRoleProvider roleProvider = webApp.GetSqlRoleProvider(SPContext.Current.Site.Zone);
                    if (roleProvider != null)
                    {
                        this.cbRoleNames.DataSource = roleProvider.GetAllRoles();
                        this.cbRoleNames.DataBind();

                        // get all roles for the user
                        string[] userRoles = roleProvider.GetRolesForUser(this.UserName);
                        foreach (var role in userRoles)
                        {
                            ListItem roleItem = this.cbRoleNames.Items.FindByText(role);
                            if (roleItem != null)
                            {
                                roleItem.Selected = true;
                            }
                        }
                    }
                }
            }

        }

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                // bind roles to the check box list
                SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                if (webApp != null)
                {
                    SqlRoleProvider roleProvider = webApp.GetSqlRoleProvider(SPContext.Current.Site.Zone);
                    if (roleProvider != null)
                    {
                        // get all roles for the user
                        string[] userRoles = roleProvider.GetRolesForUser(this.UserName);
                        List<string> removedRoles = new List<string>();
                        List<string> addedRoles = new List<string>();

                        foreach (ListItem item in this.cbRoleNames.Items)
                        {
                            // check if item is checked
                            if (!item.Selected)
                            {
                                // check if the role is selected for the user
                                if (userRoles.Any(x => x.Equals(item.Text, StringComparison.OrdinalIgnoreCase)))
                                {
                                    removedRoles.Add(item.Text);
                                }
                            }

                            // check if item is checked
                            if (item.Selected)
                            {
                                // check if the role is selected for the user
                                if (!userRoles.Any(x => x.Equals(item.Text, StringComparison.OrdinalIgnoreCase)))
                                {
                                    addedRoles.Add(item.Text);
                                }
                            }

                        }

                        // remove roles that need to be removed
                        if (removedRoles.Count > 0)
                        {
                            roleProvider.RemoveUsersFromRoles(new string[] { this.UserName }, removedRoles.ToArray());
                        }

                        // add new roles
                        if (addedRoles.Count > 0)
                        {
                            roleProvider.AddUsersToRoles(new string[] { this.UserName }, addedRoles.ToArray());
                        }
                    }
                }

                this.CloseWindow();

            }
            catch
            {

            }
        }

        /// <summary>
        /// Closes the window.
        /// </summary>
        private void CloseWindow()
        {
            if (!this.Page.ClientScript.IsStartupScriptRegistered(this.GetType(), "__SW_UserManagement_NewUser_CloseWindow"))
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "__SW_UserManagement_NewUser_CloseWindow", "window.frameElement.commitPopup();", true);
            }
        }

        /// <summary>
        /// Gets the name of the user.
        /// </summary>
        /// <value>The name of the user.</value>
        protected string UserName
        {
            get
            {
                if (String.IsNullOrEmpty(userName))
                {
                    SPWebApplication webApp = SPContext.Current.Site.WebApplication;
                    if (webApp != null)
                    {
                        SqlMembershipProvider provider = webApp.GetSqlMembershipProvider(SPContext.Current.Site.Zone);
                        if (provider != null)
                        {
                            Guid userId = new Guid(this.Page.Request.QueryString["Id"]);
                            MembershipUser user = provider.GetUser(userId, false);
                            if (user != null)
                            {
                                this.userName = user.UserName;
                            }
                        }
                    }
                }

                return this.userName;
            }
        }
    }
}
